package com.quanyan.place.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.CacheConstants;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.MD5Utils;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.ReqAdminUserVo;
import com.quanyan.place.entity.TbAcPermission;
import com.quanyan.place.entity.TbAcPermissionExample;
import com.quanyan.place.entity.TbAcResource;
import com.quanyan.place.entity.TbAcResourceExample;
import com.quanyan.place.entity.TbAcRole;
import com.quanyan.place.entity.TbAcRoleExample;
import com.quanyan.place.entity.TbAcRoleExample.Criteria;
import com.quanyan.place.entity.TbAcUserRole;
import com.quanyan.place.entity.TbAcUserRoleExample;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbAdminUserExample;
import com.quanyan.place.entity.TbDepartment;
import com.quanyan.place.entity.TbDepartmentExample;
import com.quanyan.place.entity.vo.AdminUserVo;
import com.quanyan.place.mapper.TbAcPermissionMapper;
import com.quanyan.place.mapper.TbAcResourceMapper;
import com.quanyan.place.mapper.TbAcRoleMapper;
import com.quanyan.place.mapper.TbAcUserRoleMapper;
import com.quanyan.place.mapper.TbAdminUserMapper;
import com.quanyan.place.mapper.TbDepartmentMapper;
import com.quanyan.place.mapper.VPlaceMapper;
import com.quanyan.place.service.AdminUserService;
import com.quanyan.place.utils.PlaceUtil;

/**
 * Created by yangyun on 16-6-22.
 */
@Service("adminUserService")
public class AdminUserServiceImpl implements AdminUserService{

    @Autowired
    private TbAdminUserMapper adminUserMapper;

    @Autowired
    private TbDepartmentMapper departmentMapper;
    
    @Autowired
    private TbAcUserRoleMapper tbAcUserRoleMapper;
    @Autowired
    private TbAcRoleMapper tbAcRoleMapper;
    @Autowired
    private TbAcResourceMapper tbAcResourceMapper;
    @Autowired
    private TbAcPermissionMapper tbAcPermissionMapper;

    @Autowired
    private VPlaceMapper vPlaceMapper;
    
    @Autowired
    private PlaceRedisTemplate placeCache; 
    
    @Override
    public int saveAdminUser(AdminUserVo adminUserVo) {
        int result = 0;
        if (null != adminUserVo){
            TbDepartment department = departmentMapper.selectByPrimaryKey(adminUserVo.getDeptId());
            if (null != adminUserVo.getId()){//修改用户 
                TbAdminUser tbAdminUser = adminUserMapper.selectByPrimaryKey(adminUserVo.getId());
                tbAdminUser.setGroupId(adminUserVo.getGroupId());
                tbAdminUser.setDeptId(adminUserVo.getDeptId());
                //tbAdminUser.setLoginName(adminUserVo.getLoginName());
                tbAdminUser.setTrueName(adminUserVo.getTrueName());
                tbAdminUser.setMobile(adminUserVo.getMobile());
                tbAdminUser.setGender(adminUserVo.getGender());
                tbAdminUser.setUpdateTime(Calendar.getInstance().getTime());
                tbAdminUser.setBcId(adminUserVo.getBcId());
                tbAdminUser.setBcAccountName(adminUserVo.getBcAccountName());
                tbAdminUser.setBcBank(adminUserVo.getBcBank());
                tbAdminUser.setBcCardno(adminUserVo.getBcCardno());
                tbAdminUser.setCityId(null != department ? department.getCityId() : 0);
                if (null != adminUserVo.getIsPromoter()){
                    tbAdminUser.setIsPromoter(adminUserVo.getIsPromoter());
                }
                result = adminUserMapper.updateByPrimaryKeySelective(tbAdminUser);
                if (result > 0) {
                	TbAcUserRoleExample tbAcUserRoleExample = new TbAcUserRoleExample();
                	tbAcUserRoleExample.createCriteria().andUserIdEqualTo(tbAdminUser.getId());
                	List<TbAcUserRole> oldRoles = tbAcUserRoleMapper.selectByExample(tbAcUserRoleExample);
                	
                	List<Integer> oldRoleIds  = new ArrayList<Integer>(Collections2.transform(oldRoles, new Function<TbAcUserRole, Integer>() {
						@Override
						public Integer apply(TbAcUserRole input) {
							return input.getId();
						}
					}));
                	List<Integer> newRoleIds = adminUserVo.getRoles();
                	if (oldRoleIds.size() != newRoleIds.size() || !newRoleIds.containsAll(oldRoleIds)) {//角色发生改变  刷新缓存
                		//删除用户旧的角色
                		tbAcUserRoleMapper.deleteByExample(tbAcUserRoleExample);
                		//新增用户新角色
                		for (Integer roleId : newRoleIds) {
                			TbAcUserRole tbAcUserRole = new TbAcUserRole();
                			tbAcUserRole.setUserId(tbAdminUser.getId());
                			tbAcUserRole.setRoleId(roleId);
                			tbAcUserRole.setCreateTime(new Date());
                			tbAcUserRole.setUpdateTime(new Date());
                			tbAcUserRoleMapper.insertSelective(tbAcUserRole);
						}
                		
                		TbAdminUser cacheTbAdminUser  = (TbAdminUser) placeCache.get(CacheConstants.PLACE_COMMON_DATA + tbAdminUser.getId().toString());
                		if (cacheTbAdminUser != null) {
                			List<TbAcResource> tbAcResourceList = adminUserMapper.getUserResource(tbAdminUser.getId());
                			cacheTbAdminUser.setResourceList(PlaceUtil.convertToTree(tbAcResourceList));
                			placeCache.set(CacheConstants.PLACE_COMMON_DATA + tbAdminUser.getId().toString(),cacheTbAdminUser);
                		}
                	}
                }
            } else {//添加用户  -- 登录时再去刷新权限缓存
                TbAdminUser tbAdminUser = new TbAdminUser();
                if(StringUtils.isNotEmpty(adminUserVo.getMobile())) tbAdminUser.setMobile(adminUserVo.getMobile());
                if(StringUtils.isNotEmpty(adminUserVo.getTrueName())) tbAdminUser.setTrueName(adminUserVo.getTrueName());
                if (StringUtils.isNotEmpty(adminUserVo.getPassword())){tbAdminUser.setPassword(MD5Utils.MD5Encode(adminUserVo.getPassword()));}
                tbAdminUser.setGroupId(adminUserVo.getGroupId());
                tbAdminUser.setCityId(null != department ? department.getCityId() : 0);
                tbAdminUser.setBcId(adminUserVo.getBcId());
                tbAdminUser.setBcAccountName(adminUserVo.getBcAccountName());
                tbAdminUser.setBcBank(adminUserVo.getBcBank());
                tbAdminUser.setBcCardno(adminUserVo.getBcCardno());
                tbAdminUser.setDeptId(adminUserVo.getDeptId());
                tbAdminUser.setLoginName(adminUserVo.getLoginName());
                tbAdminUser.setGender(adminUserVo.getGender());
                tbAdminUser.setChannelId(PlaceConstants.SOURCE_PLACE_BUSINESS);
                tbAdminUser.setLoginCount(0);
                tbAdminUser.setIsDelete(Constants.IS_DELETE_FALSE);
                tbAdminUser.setCreateTime(Calendar.getInstance().getTime());
                tbAdminUser.setUpdateTime(Calendar.getInstance().getTime());
                if (null != adminUserVo.getIsPromoter()){
                    tbAdminUser.setIsPromoter(adminUserVo.getIsPromoter());
                }
                result = adminUserMapper.insertSelective(tbAdminUser);
                if (result > 0) {//写入用户角色关系
                	if (!CollectionUtils.isEmpty(adminUserVo.getRoles())) {
                		for (Integer roleId : adminUserVo.getRoles()) {
    						TbAcUserRole tbAcUserRole = new TbAcUserRole();
    						tbAcUserRole.setUserId(tbAdminUser.getId());
    						tbAcUserRole.setRoleId(roleId);
    						tbAcUserRole.setCreateTime(new Date());
    						tbAcUserRole.setUpdateTime(new Date());
    						tbAcUserRoleMapper.insertSelective(tbAcUserRole);
    					}
					}
                }
            }
        }
        return result;
    }

    /**
     * 密码重置
     * @param adminUserVo
     * @return
     */
    @Override
    public int updateUserPassword(AdminUserVo adminUserVo) {
        int result = 0;
        TbAdminUser tbAdminUser = adminUserMapper.selectByPrimaryKey(adminUserVo.getId());
        tbAdminUser.setPassword(MD5Utils.MD5Encode(adminUserVo.getPassword()));
        tbAdminUser.setUpdateTime(Calendar.getInstance().getTime());
        result = adminUserMapper.updateByPrimaryKeySelective(tbAdminUser);
        return result;
    }

    @Override
    public List<TbDepartment> getDeptList(Integer parentId) {
        TbDepartmentExample example=new TbDepartmentExample();
        if(parentId != null){
            example.createCriteria().andParentIdEqualTo(parentId);
        }
        List<TbDepartment> deptList = departmentMapper.selectByExample(example);
        return deptList;
    }

    /**
     * 获取后台登录用户
     * @return
     */
    public TbAdminUser getAdminUser(Integer uid){
        return adminUserMapper.selectByPrimaryKey(uid);
    }

    @Override
    public PageObj<List<TbAdminUser>> getAdminUserList(ReqAdminUserVo reqAdminUserVo) {
        TbAdminUserExample example=new TbAdminUserExample();
        TbAdminUserExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        
        TbAdminUserExample.Criteria criteria1 = example.or();
        TbAdminUserExample.Criteria criteria2 = example.or();
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (null != reqAdminUserVo){
        	String key = reqAdminUserVo.getKey();
        	
            if (null != reqAdminUserVo.getCityId()){
                criteria.andCityIdEqualTo(reqAdminUserVo.getCityId());
                if (!StringUtils.isBlank(key)) {
                	criteria1.andCityIdEqualTo(reqAdminUserVo.getCityId());
                	criteria2.andCityIdEqualTo(reqAdminUserVo.getCityId());
    			}
            }
            if (null != reqAdminUserVo.getGroupId()){
                criteria.andGroupIdEqualTo(reqAdminUserVo.getGroupId());
                if (!StringUtils.isBlank(key)) {
                    criteria1.andGroupIdEqualTo(reqAdminUserVo.getGroupId());
                    criteria2.andGroupIdEqualTo(reqAdminUserVo.getGroupId());
    			}
            }
            
            if (!StringUtils.isBlank(key)) {
        	  criteria2.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
              criteria1.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
              criteria.andTrueNameLike("%" + key + "%");
              criteria1.andMobileLike("%" + key + "%");
              criteria2.andLoginNameLike("%" + key + "%");
            }
            
            if (null != reqAdminUserVo.getPageNum()){
                pageNum = reqAdminUserVo.getPageNum();
            }
            if (null != reqAdminUserVo.getPageSize()){
                pageSize = reqAdminUserVo.getPageSize();
            }
        }
        int total =adminUserMapper.countByExample(example);
        example.setOrderByClause("id desc");
        example.setPage(new Page(pageNum * pageSize, pageSize,total));
        List<TbAdminUser> userList = adminUserMapper.selectByExample(example);
        PageObj<List<TbAdminUser>> result = PageObj.create(total, pageNum, pageSize, userList);
        return result;
    }

    /**
     * 更新密码
     * @param uid
     * @param oldPassword
     * @param newPassword
     * @param rePassword
     * @return
     */
    public APIResponse userPasswordUpdate(Integer uid, String oldPassword,String newPassword, String rePassword) {

        List<String> errMsg = new ArrayList<String>();
        if (StringUtils.isNotEmpty(newPassword) && !newPassword.equals(rePassword)){
            errMsg.add("两次输入的密码不一致");
        }
        if (errMsg.size() > 0){
            return APIResponse.returnFail(errMsg.toString());
        }
        TbAdminUser dbUser = null;
        if(uid > 0){
            dbUser = adminUserMapper.selectByPrimaryKey(uid);
            if (dbUser!= null && dbUser.getPassword() != null && dbUser.getPassword().equals(MD5Utils.MD5Encode(oldPassword))){
                dbUser.setPassword(MD5Utils.MD5Encode(newPassword));
                adminUserMapper.updateByPrimaryKeySelective(dbUser);
            } else {
                errMsg.add("旧密码不正确");
            }
        }
        if (errMsg.size() > 0){
            return APIResponse.returnFail(errMsg.toString());
        }
        return APIResponse.returnSuccess("操作成功!");
    }

    @Override
    public AdminUserVo getAdminUserById(Integer id) {
        TbAdminUserExample example=new TbAdminUserExample();
        TbAdminUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        List<TbAdminUser> userList = adminUserMapper.selectByExample(example);
        if (userList!=null&&userList.size()>0){
            AdminUserVo vo=new AdminUserVo();
            vo.setId(userList.get(0).getId());
            vo.setMobile(userList.get(0).getMobile());
            vo.setDeptId(userList.get(0).getDeptId());
            vo.setLoginName(userList.get(0).getLoginName());
            vo.setTrueName(userList.get(0).getTrueName());
            vo.setGender(userList.get(0).getGender());
            vo.setGroupId(userList.get(0).getGroupId());
            if (null != userList.get(0).getBcId()){
                vo.setBcId(userList.get(0).getBcId());
            }
            if (null != userList.get(0).getBcAccountName()){
                vo.setBcAccountName(userList.get(0).getBcAccountName());
            }
            if (null != userList.get(0).getBcCardno()){
                vo.setBcCardno(userList.get(0).getBcCardno());
            }
            if (null != userList.get(0).getIsPromoter()){
                vo.setIsPromoter(userList.get(0).getIsPromoter());
            }else{
                vo.setIsPromoter(PlaceConstants.NO);
            }
            if (this.getDepartmentById(userList.get(0).getDeptId())!=null){
                 vo.setDeptName(this.getDepartmentById(userList.get(0).getDeptId()).getDeptName());
            }
            
            List<TbAcRole>  allRoles = getRoles(null);
            List<TbAcRole> useRoles = getRoleByUser(vo.getId());
            
            Iterator<TbAcRole> allRolesIterator = allRoles.iterator();
            while (allRolesIterator.hasNext()) {
            	TbAcRole tbAcRole = allRolesIterator.next();
            	if ("系统管理员".equals(tbAcRole.getName()) 
            			&& (useRoles == null || !useRoles.contains(tbAcRole))) {
            		allRolesIterator.remove();
				}
            	if (useRoles != null && useRoles.contains(tbAcRole)) {
					tbAcRole.setChecked(true);
				}
			}
            vo.setRoleList(allRoles);
            return  vo;
        }
        return null;
    }

    public TbDepartment getDepartmentById(Integer id) {
        TbDepartment department = departmentMapper.selectByPrimaryKey(id);
        return department;
    }

    @Override
    public void updateUserInfo(AdminUserVo aVo) {
        TbAdminUserExample example=new TbAdminUserExample();
        TbAdminUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(aVo.getId());
        TbAdminUser vo=new TbAdminUser();
        vo.setMobile(aVo.getMobile());
        vo.setTrueName(aVo.getTrueName());
        vo.setGender(aVo.getGender());
        vo.setGroupId(aVo.getGroupId());
        vo.setDeptId(aVo.getDeptId());
        vo.setBcId(aVo.getBcId());
        vo.setBcBank(aVo.getBcBank());
        vo.setBcCardno(aVo.getBcCardno());
        vo.setBcAccountName(aVo.getBcAccountName());
        if (null != aVo.getIsPromoter()){
            vo.setIsPromoter(aVo.getIsPromoter());
        }
        adminUserMapper.updateByExampleSelective(vo,example);
    }

    @Override
    public boolean existsUser(AdminUserVo adminUserVo) {
        TbAdminUserExample example=new TbAdminUserExample();
        TbAdminUserExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andLoginNameEqualTo(adminUserVo.getLoginName());
        if (null != adminUserVo.getId()){
            criteria.andIdNotEqualTo(adminUserVo.getId());
        }
        List<TbAdminUser> userList = adminUserMapper.selectByExample(example);
        if (null != userList && userList.size() > 0){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取未授权的供应商用户  {groupId = 23}
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageObj<List<TbAdminUser>> getSupplierUserList(Integer pageNum, Integer pageSize,Integer groupId) {
        if (null == pageNum){
            pageNum = 0;
        }
        if (null == pageSize){
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        if (null == groupId){
            groupId = 23;//供应商用户标识
        }
        Integer total = vPlaceMapper.countAdminUserForSupplier(groupId);
        List<TbAdminUser> tbAdminUsers = vPlaceMapper.selectAdminUserForSupplier(groupId,pageNum,pageSize);
        PageObj<List<TbAdminUser>> result = PageObj.create(total, pageNum, pageSize, tbAdminUsers);
        return result;
    }

	@Override
	public List<TbAcResource> getUserResource(Integer userId) {
		return adminUserMapper.getUserResource(userId);
	}

	@Override
	public List<TbAcRole> getRoles(TbAcRole tbAcRole) {
		TbAcRoleExample tbAcRoleExample = new TbAcRoleExample();
		Criteria criteria = tbAcRoleExample.createCriteria();
		//criteria.andIsEffectiveEqualTo((byte)1);
		
		if (tbAcRole != null) {
			if (StringUtils.isNotBlank(tbAcRole.getName())) {
				criteria.andNameLike("%"+tbAcRole.getName()+"%");
			}
			
			if (tbAcRole.getId() != null && tbAcRole.getId() > 0) {
				criteria.andIdEqualTo(tbAcRole.getId());
			}
			//添加用户时候，不能添加系统管理员用户
			if (tbAcRole.getId() != null && tbAcRole.getId() == 0) {
				criteria.andNameNotEqualTo("系统管理员");
			}
		}
		return tbAcRoleMapper.selectByExample(tbAcRoleExample);
	}

	@Override
	public List<TbAcResource> getAllResources() {
		List<TbAcResource> result = new ArrayList<TbAcResource>();
		
		TbAcResourceExample tbAcResourceExample = new TbAcResourceExample();
		tbAcResourceExample.createCriteria().andIsShowEqualTo((byte)1);
		
		List<TbAcResource> tbAcResourceList = tbAcResourceMapper.selectByExample(tbAcResourceExample);
		if (CollectionUtils.isNotEmpty(tbAcResourceList)) {
			
			Map<String,TbAcResource> map = Maps.uniqueIndex(tbAcResourceList, new Function<TbAcResource, String>() {
				@Override
				public String apply(TbAcResource input) {
					return input.getCode();
				}
			});
			
			for (TbAcResource tbAcResource : tbAcResourceList) {
				String  parentCode = tbAcResource.getParentCode();
				TbAcResource parentResource = map.get(parentCode);
				if (parentResource != null) {
					parentResource.getChildren().add(tbAcResource);
				} else {//为空即顶级菜单
					result.add(tbAcResource);
				}
			}
		}
          return result; 		
	}

	@Override
	public List<TbAcResource> getResourceByRole(Integer roleId) {

		TbAcResourceExample tbAcResourceExample = new TbAcResourceExample();
		tbAcResourceExample.createCriteria().andIsShowEqualTo((byte)1);
		List<TbAcResource> result = tbAcResourceMapper.selectByExample(tbAcResourceExample);
		
		Map<String,TbAcResource> map = new HashMap<String, TbAcResource>();
		
		TbAcPermissionExample tbAcPermissionExample = new TbAcPermissionExample();
		tbAcPermissionExample.createCriteria().andRoleIdEqualTo(roleId);
		List<TbAcPermission> tbAcPermissionList = tbAcPermissionMapper.selectByExample(tbAcPermissionExample);
		if (CollectionUtils.isNotEmpty(tbAcPermissionList)) {
			for (TbAcPermission tbAcPermission : tbAcPermissionList) {
				tbAcResourceExample.clear();
				tbAcResourceExample.createCriteria().andIdEqualTo(tbAcPermission.getResourceId());
				
				 List<TbAcResource> tbAcResourceList =  tbAcResourceMapper.selectByExample(tbAcResourceExample);
				 if (CollectionUtils.isNotEmpty(tbAcResourceList)) {
					for (TbAcResource tbAcResource : tbAcResourceList) {
						map.put(tbAcResource.getCode(), tbAcResource);
					}
				 }
			}
			
			if (!map.isEmpty()) {
				for (TbAcResource tbAcResource : result) {
					if (map.containsKey(tbAcResource.getCode())) {
						tbAcResource.setChecked(true);
					}
				}
			}
		}
		
		return PlaceUtil.convertToTree(result);
	}

	@Override
	public List<TbAcRole> getRoleByUser(Integer userId) {
		List<TbAcRole> result = new ArrayList<TbAcRole>();
		
		TbAcUserRoleExample tbAcUserRoleExample = new TbAcUserRoleExample();
		tbAcUserRoleExample.createCriteria().andUserIdEqualTo(userId);
		
		List<TbAcUserRole> tbAcUserRoleList = tbAcUserRoleMapper.selectByExample(tbAcUserRoleExample);
		if (CollectionUtils.isNotEmpty(tbAcUserRoleList)) {
			for (TbAcUserRole tbAcUserRole : tbAcUserRoleList) {
				TbAcRoleExample tbAcRoleExample = new TbAcRoleExample();
				tbAcRoleExample.createCriteria().andIdEqualTo(tbAcUserRole.getRoleId());
				
				List<TbAcRole> tbAcRoleList = tbAcRoleMapper.selectByExample(tbAcRoleExample);
				if (CollectionUtils.isNotEmpty(tbAcRoleList)) {
					result.addAll(tbAcRoleList);
				}
			}
		}
		return result;
	}
	
	@Async
	public void refreshPermisson(Integer roleId){
		TbAcUserRoleExample tbAcUserRoleExample = new TbAcUserRoleExample();
		tbAcUserRoleExample.createCriteria().andRoleIdEqualTo(roleId);
		
		List<TbAcUserRole> TbAcUserRoleList = tbAcUserRoleMapper.selectByExample(tbAcUserRoleExample);
		//TbAcRole tbAcRole = tbAcRoleMapper.selectByPrimaryKey(roleId);
//		if (tbAcRole.getIsEffective() == 0) {//无效角色  
//			//删除用户角色关系
//			tbAcUserRoleMapper.deleteByExample(tbAcUserRoleExample);
//			//删除角色权限关系
//			TbAcPermissionExample tbAcPermissionExample = new TbAcPermissionExample();
//			tbAcPermissionExample.createCriteria().andRoleIdEqualTo(roleId);
//			tbAcPermissionMapper.deleteByExample(tbAcPermissionExample);
//		}
		//刷新已登录的用户权限缓存
		if (CollectionUtils.isNotEmpty(TbAcUserRoleList)) {
			for (TbAcUserRole tbAcUserRole : TbAcUserRoleList) {
				Integer userId = tbAcUserRole.getUserId();
        		TbAdminUser cacheTbAdminUser  = (TbAdminUser) placeCache.get(CacheConstants.PLACE_COMMON_DATA + userId.toString());
        		if (cacheTbAdminUser != null) {//已登录
        			List<TbAcResource> tbAcResourceList = adminUserMapper.getUserResource(userId);
        			cacheTbAdminUser.setResourceList(PlaceUtil.convertToTree(tbAcResourceList));
        			placeCache.set(CacheConstants.PLACE_COMMON_DATA + userId.toString(),cacheTbAdminUser);
        		}
			}
		}
	}

	@Override
	@Transactional
	public void saveAdminPermission(Integer roleId, List<Integer> resoureIds) {
		TbAcPermissionExample tbAcPermissionExample = new TbAcPermissionExample();
		tbAcPermissionExample.createCriteria().andRoleIdEqualTo(roleId);
		if (CollectionUtils.isNotEmpty(resoureIds)) {
			//先删除旧的该角色权限
			tbAcPermissionMapper.deleteByExample(tbAcPermissionExample);
			
			List<TbAcPermission>  tbAcPermissionList = new ArrayList<TbAcPermission>();
			for (Integer resourceId : resoureIds) {
				TbAcPermission tbAcPermission  = new TbAcPermission();
				tbAcPermission.setRoleId(roleId);
				tbAcPermission.setResourceId(resourceId);
				tbAcPermission.setCreateTime(new Date());
				tbAcPermission.setUpdateTime(new Date());
				tbAcPermissionList.add(tbAcPermission);
			}
			tbAcPermissionMapper.batchInsert(tbAcPermissionList);
			
			//异步刷新用户缓存
			refreshPermisson(roleId);
		}
	}

	@Override
	@Transactional
	public void saveAdminRole(TbAcRole tbAcRole) {
		if (tbAcRole != null) {
			if (tbAcRole.getId() != null) {//更新角色
				TbAcRole oldTbAcRole = tbAcRoleMapper.selectByPrimaryKey(tbAcRole.getId());
				oldTbAcRole.setBrief(tbAcRole.getBrief());
				oldTbAcRole.setIsEffective(tbAcRole.getIsEffective());
				oldTbAcRole.setName(tbAcRole.getName());
				tbAcRoleMapper.updateByPrimaryKeySelective(oldTbAcRole);
				
				if (!tbAcRole.getIsEffective().equals(oldTbAcRole.getIsEffective())) {
					//异步刷新用户缓存
					refreshPermisson(tbAcRole.getId());
				}
				
			} else {//添加角色
				tbAcRole.setIsEffective((byte)1);//有效
				tbAcRole.setCreateTime(new Date());
				tbAcRole.setUpdateTime(new Date());
				tbAcRoleMapper.insert(tbAcRole);
			}
		}
	}
}
